from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QDialog, QDialogButtonBox, QGridLayout, QLabel, QLineEdit, QMessageBox, QTextEdit, QVBoxLayout

'''
新建Form-使用@property对外暴露字段属性（只读）
'''


class AddDialogWidget(QDialog):
    """ A dialog to add a new address to the addressbook. """

    def __init__(self, parent=None):
        super().__init__(parent)

        name_label = QLabel("Name")
        address_label = QLabel("Address")


        self._name_text = QLineEdit()
        self._address_text = QTextEdit()

        grid = QGridLayout()
        grid.addWidget(name_label, 0, 0)
        grid.addWidget(self._name_text, 0, 1)

        # 注意布局定位效果
        grid.addWidget(address_label, 1, 0, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) # 默认是 栅格 内垂直居中
        # grid.addWidget(address_label, 1, 0)
        grid.addWidget(self._address_text, 1, 1)
        # grid.addWidget(self._address_text, 1, 1, Qt.AlignmentFlag.AlignLeft)

        grid.setColumnStretch(1, 2) # 第二列列宽扩展

        button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        button_box.button(QDialogButtonBox.StandardButton.Ok).setDefault(True) # 设置默认按钮（如果不设置一般以第一个Yes类按钮为默认按钮）

        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(button_box)
        self.setLayout(layout)
        self.setWindowTitle("Add a Contact")

        # QDialogButtonBox.accepted() This signal is emitted when a button inside the button box is clicked, as long as it was defined with the AcceptRole or YesRole .
        # QDialog.accept() Hides the modal dialog and sets the result code to Accepted.
        button_box.accepted.connect(self.accept) # 将用户点击按钮的结果反馈到Dialog的result上
        button_box.rejected.connect(self.reject)

    # @property 只读属性定义
    # These properties make using this dialog a little cleaner. It's much
    # nicer to type "addDialog.address" to retrieve the address as compared
    # to "addDialog.addressText.toPlainText()"
    @property
    def name(self):
        return self._name_text.text()

    @property
    def address(self):
        return self._address_text.toPlainText()

    def accept(self):
        """重写accept方法以验证输入"""
        if not self._name_text.text().strip() or not self._address_text.toPlainText().strip():
            QMessageBox.warning(self, "警告", "输入字段不能为空")
            return
        super().accept()

if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    dialog = AddDialogWidget()
    # dialog = QDialog()
    dialog.setWindowTitle("new address dialog")
    # dialog.setWindowTitle("standard Dialog")
    # dialog.show() # 闪屏
    # print("闪屏-无阻塞，立即执行")
    result = dialog.exec()  # Blocks until the dialog is closed。Returns QDialog.Accepted or QDialog.Rejected
    print(f"result: {result}")
    if result:
        name = dialog.name
        address = dialog.address
        print(f"Name: {name}")
        print(f"Address: {address}")
